using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Christian.Helle.PocketNews.PocketPC.NewsProtocol
{
	class Utilites
	{
		/// <summary>
		/// Parse the strings in the newsgroup article's header; Encoding-aware
		/// </summary>
		/// <param name="s">The header string to be decoded</param>
		/// <returns>The decoded string in the system default encoding</returns>
		public static string DecodeHeaderString(string s)
		{
			Match header = Regex.Match(s, @".?=\?(.+)\?(.+)\?(.+)\?=");
			if (header.Success)
			{
				string charset = header.Groups[1].Value;
				string user_encoding = header.Groups[2].Value;
				string text = header.Groups[3].Value;
				byte[] bytArray;
			
				switch (user_encoding)
				{
					case "B":
						bytArray = Convert.FromBase64String(text);
						break;
					case "Q":				
						bytArray = NewsProtocol.Utilites.GetByteArray(text);
						break;
					default:
						bytArray = Encoding.Default.GetBytes(text);
						break;
				}
				
				Encoding encoding = System.Text.Encoding.Default;
				text = encoding.GetString(bytArray, 0, bytArray.Length);

				int index = s.IndexOf("=?");
				string str = s.Substring(0, index);

				if ( index != 0 )
					text = string.Join("", new string[] { s.Substring(0, index), text } );

				int end;
				if ( s.EndsWith("?=") == false )
				{
					end = s.LastIndexOf("?=");
					string strEnd = s.Substring(end + 2, s.Length - end - 2 );
					text = string.Join("", new string[] { text, strEnd } );
				}

				return text;
			}
			else
				return s;
		}

		/// <summary>
		/// Convert a Quoted Printable string into Byte Array
		/// </summary>
		/// <param name="s">string encoded in QP format</param>
		/// <returns>A byte array containing each character in 
		/// the string parameter in byte format</returns>
		public static byte[] GetByteArray(string s)
		{
			byte[] buffer=new byte[s.Length];

			int bufferPosition=0;
			for(int i=0;i<s.Length;i++)
			{
				if (s[i]=='=')
				{
					if (s[i+1]=='\r' && s[i+2]=='\n')
						bufferPosition--;
					else
						buffer[bufferPosition]=System.Convert.ToByte(s.Substring(i+1,2),16);
					i+=2;
				}
				else if (s[i]=='_')
					buffer[bufferPosition]=32;
				else
					buffer[bufferPosition]=(byte)s[i];
				bufferPosition++;
			}
			byte[] newArray=new byte[bufferPosition];
			Array.Copy(buffer,newArray,bufferPosition);
			return newArray;
		}
	}
}
